<script lang="ts">
import {defineComponent, reactive, computed, ref} from "vue"
import type {PropType} from "vue"
import {ResourceLibraryType} from "./../config"
import {UploadConfigType, UploadFile} from "@/units/upload"
import {UnwrapNestedRefs} from "@vue/reactivity"
import {ElMessage} from 'element-plus'
import {recordRepositoryApi} from "@/api/resources";

export default defineComponent({
  name: "UploadProgress",
  emits: {
    remove: (index: number) => true,
    choice: () => true,
    clear: () => true,
    close: () => true
  },
  props: {
    type: {//上传类别
      type: String as PropType<ResourceLibraryType>,
      required: true
    },
    files: {//文件对象
      type: Array as PropType<Array<File>>,
      required: true
    },
    uploadConf: {//上传配置
      type: Object as PropType<UploadConfigType>,
      required: true
    },
    classify: {//资源分类
      type: Array as PropType<{ id: number, name: string }[]>,
      default: []
    }
  },
  setup(props, {emit}) {
    /**
     * 当前要上传的分类
     */
    const classify_id = ref<number>(0)

    /**
     * 上传状态
     */
    const upload: UnwrapNestedRefs<{ status: boolean, current: number, progress: Array<number> }> = reactive({
      status: false,//false待上传  true已上传
      current: 0,//当前上传的文件索引
      progress: [],//上传文件的记录
    })


    /**
     * 移除文件
     */
    function removeFile(index: number) {
      emit('remove', index)
    }

    /**
     *  继续选择文件
     * @constructor
     */
    function ChoiceFile() {
      emit('choice')
    }

    /**
     *  清空文件
     * @constructor
     */
    function clearFile() {
      emit('clear')
    }

    /**
     * 开始上传资源
     * @constructor
     */
    async function StartUpload() {
      console.log(props.uploadConf);
      upload.status = true
      let error = 0
      let success = 0
      let record: any[] = []
      for (let i in props.files) {
        const index = parseInt(i)
        const file = props.files[i]
        const result = await UploadFile(file, props.uploadConf, progress => upload.progress[index] = progress)
        if (result) {
          success++
          record.push({...result, type: props.type, size: file.size, name: file.name, cate_id: classify_id.value})
        } else {
          error++
        }
      }
      if (success > 0 && error === 0) {
        ElMessage.success(`${success}个文件上传成功,${error}个上传成功`)
      } else if (success > 0) {
        ElMessage.success(`${success}个文件上传成功`)
      } else {
        ElMessage.error(`没有上传成功的文件`)
      }
      if (record.length > 0) {
        await recordRepositoryApi(record)
      }
      emit('close')
    }

    /**
     * 上传可选分类
     */
    const classifyList = computed(() => {
      return [{id: 0, name: "默认分类"}].concat(props.classify)
    });

    return {
      removeFile, ChoiceFile, clearFile, StartUpload, upload, classifyList, classify_id
    }
  }
})
</script>

<template>
  <div class="upload-progress">
    <el-table height="450px" border :data="files">
      <el-table-column prop="name" show-overflow-tooltip label="名称">
        <template #default="{row,$index}">
          <app-progress :progress="upload.progress[$index]?upload.progress[$index]:0">
            {{ row.name }}
          </app-progress>
        </template>
      </el-table-column>
      <el-table-column prop="size" align="center" label="大小" width="100px">
        <template #default="{row}">
          <file-size :size="row.size"></file-size>
        </template>
      </el-table-column>
      <el-table-column label="#" width="50" align="center">
        <template #default="{$index}">
          <app-icon @click="removeFile($index)" class="app-tap" size="18" color="#ff0000" name="Close"></app-icon>
        </template>
      </el-table-column>
    </el-table>
    <div class="up-toolist app-margin-top-large">
      <div v-if="upload.status">
        <el-link class="app-margin-right-large" type="danger">
          正在上传中,不要关闭或离开当前页面
        </el-link>
        <el-button type="success">
          正在上传{{ files.length }} / {{ upload.progress.length }}
        </el-button>
      </div>
      <div v-else>
        <el-button type="danger" @click="clearFile">清空选择</el-button>
        <el-button type="primary" @click="ChoiceFile">继续选择</el-button>
        <el-select class="app-width-p200 app-margin-left-medium" v-model="classify_id">
          <template #prefix>上传到:</template>
          <template #default>
            <el-option v-for="item in classifyList" :key="item.id" :value="item.id" :label="item.name"/>
          </template>
        </el-select>
        <el-button type="success" @click="StartUpload">开始上传</el-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.upload-progress {
  .up-toolist {
    text-align: right;
  }
}
</style>
